﻿#include"XQSystemInfoLabel.h"
#include"XSystemInfo.h"
#include"XQMouseEventFilter_Press.hpp"
#include<QMenu>
#include<QTimer>
QDateTime XQSystemInfoLabel::m_startTime= QDateTime::currentDateTime();
XQSystemInfoLabel::XQSystemInfoLabel(QWidget* parent)
	:QLabel(parent)
{
	init();
}

XQSystemInfoLabel::~XQSystemInfoLabel()
{
}

QString XQSystemInfoLabel::runTime() const
{
	qint64 mSecs = QDateTime::currentDateTime().toMSecsSinceEpoch() - m_startTime.toMSecsSinceEpoch();
	int days = mSecs / 86400000;
	return QString("%1天").arg(days) + QTime::fromMSecsSinceStartOfDay(mSecs % 86400000).toString("hh时mm分ss秒");
}

void XQSystemInfoLabel::showAll()
{
	m_cpu = true;
	m_memory = true;
	m_runTime = true;
}

void XQSystemInfoLabel::init()
{
	m_timer = new QTimer(this);
	m_timer->callOnTimeout(this,&XQSystemInfoLabel::showText);
	m_timer->start(1000);
	installEventFilter(new XQMouseEventFilter_Press([=]
		{contextMenuRequested();}, Qt::MouseButton::RightButton, this));
}

void XQSystemInfoLabel::showText()
{
	auto& sysyem = XSystemInfo::instance();
	QString text;
	if (m_cpu)
		text += QString("CPU:%1% ").arg(QString::number(sysyem.cpuLoadAverage(),'f',2));
	if(m_memory)
		text += QString("内存:%1% ").arg(QString::number(sysyem.memoryUsed(),'f',2));
	if (m_runTime)
		text += runTime();
	if (text.endsWith(" "))
		text.remove(text.size() - 1, 1);
	setText(text);
}

void XQSystemInfoLabel::contextMenuRequested()
{
	QMenu* menu = new QMenu(this);
	menu->setAttribute(Qt::WA_DeleteOnClose);
	//cpu负载
	if (m_cpu)
		menu->addAction("隐藏cpu利用率", [this] {m_cpu = false; });
	else 
		menu->addAction("显示cpu利用率", [this] {m_cpu = true; });
	//内存
	if (m_memory)
		menu->addAction("隐藏内存使用率", [this] {m_memory = false; });
	else
		menu->addAction("显示内存使用率", [this] {m_memory = true; });
	//运行时间
	if (m_runTime)
		menu->addAction("隐藏运行时间", [this] {m_runTime = false; });
	else
		menu->addAction("显示运行时间", [this] {m_runTime = true; });
	menu->popup(QCursor::pos());
}
